$(document).ready(function () {
    $(window).on('load', function () {
        wdt = $("#conteudo").width() - 15;
        $('#dg').datagrid({
            width: wdt
        }).datagrid('reload');
    });
    $(window).on('resize', function () {
        wdt = $("#conteudo").width() - 15;
        $('#dg').datagrid({
            width: wdt
        }).datagrid('reload');
    });
    var url;
    $('.new').click(function (e) {
        e.preventDefault(e);
        $('#dlg').dialog('open').dialog('setTitle', 'Nova Disciplina');
        $('#fm').form('clear');
        url = './gerenciar/novadcp';
        return false;
    });
    $('.edit').click(function (e) {
        e.preventDefault(e);
        var row = $('#dg').datagrid('getSelected');
        if (row) {
            $('#dlg').dialog('open').dialog('setTitle', 'Editar disciplina');
            $('#fm').form('load', row);
            url = './gerenciar/editardcp/?id=' + row.id;
        } else {
            swal("Ooops!", "Selecione uma disciplina para editar", "error");
        }
        return false;
    });
    $('.cancl').click(function (e) {
        e.preventDefault(e);
        $('#dlg').dialog('close');
        return false;
    });
    $('.save').click(function (e) {
        e.preventDefault(e);
        $('#fm').form('submit', {
            url: url,
            onSubmit: function () {
                return $(this).form('validate');
            },
            success: function (result) {
                var result = eval('(' + result + ')');
                if (result.errorMsg) {
                    swal("Ooops!", result.errorMsg, "error");
                } else {
                    $('#dlg').dialog('close');        // close the dialog
                    $('#dg').datagrid('reload');    // reload the user data
                }
            }
        });
        return false;
    });
    $('.remove').click(function (e) {
        e.preventDefault(e);
        var row = $('#dg').datagrid('getSelected');
        if (row) {
            $.messager.confirm('Confirmar exclusão', 'Deseja realmente remover esta disciplina?', function (r) {
                if (r) {
                    $.post('./gerenciar/removerdcp/', {id: row.id}, function (result) {
                        if (result.success) {
                            $('#dg').datagrid('reload');    // reload the user data
                        } else {
                            swal("Ooops!", result.errorMsg, "error");
                        }
                    }, 'json');
                }
            });
        } else {
            swal("Ooops!", "Selecione uma disciplina para remover", "error");
        }
        return false;
    });
});